package com.example.kafka.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.http.client.reactive.ReactorResourceFactory;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.netty.http.client.HttpClient;

import java.net.URI;

/**
 * all web client configuration
 *
 * @author lingGao
 */
@Configuration
public class WebClientConfig {

    /**
     * web client for full-dose-monitor open api
     *
     * @return web client for full-dose-monitor open api
     */
    @Bean("fullMonitorWebClient")
    public WebClient fullMonitorWebClient(FullDoseMonitorProperties properties) {
        // http client
        HttpClient httpClient = HttpClient.create()
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                                .doOnConnected(conn -> conn
                                        .addHandlerLast(new ReadTimeoutHandler(60 * 10))
                                        .addHandlerLast(new WriteTimeoutHandler(60 * 10))
                                );


        // uri
        DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(UriComponentsBuilder.newInstance()
                .uri(URI.create("http://60.60.60.207:30012")));

        // create common web client
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .uriBuilderFactory(uriBuilderFactory)
                .build();
    }

    @Bean
    public ReactorResourceFactory reactorResourceFactory() {
        return new ReactorResourceFactory();
    }


}
